package com.xbdun.web.validatebmp.facade.code;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.xbdun.common.api.XbdUnStringResult;
import com.xbdun.common.exceptions.BizException;
import com.xbdun.facade.validatebmp.request.ValidateCodeRequest;
import com.xbdun.facade.validatebmp.service.code.VeriCodeValiFacade;
import com.xbdun.web.validatebmp.utils.code.VeriCodeUtil;

import lombok.extern.slf4j.Slf4j;

//机构部门
@Component
@Slf4j
public class VeriCodeValiFacadeImpl implements VeriCodeValiFacade{
	@Autowired
	StringRedisTemplate stringRedisTemplate;
	/**
	* @Title: validateCode
	* @Description	验证码的校验
	* @param request
	* @return XbdUnStringResult    返回类型
	 */
	public XbdUnStringResult validateCode(ValidateCodeRequest request){
		XbdUnStringResult result = new XbdUnStringResult();
		try{
			log.info("start 对比验证码是否合法,入参={}",request);
			result.setBizException(BizException.PARAM_CHKE_FAIL.newInstance("验证码校验失败"));
			if(StringUtils.isBlank(request.getVeriKey())){
				throw BizException.PARAM_CHKE_FAIL.newInstance("验证码KEY不能为空");
			}
			if(StringUtils.isBlank(request.getVeriCode())){
				throw BizException.PARAM_CHKE_FAIL.newInstance("验证码值不能为空");
			}
			//转换为大写
			request.setVeriCode(request.getVeriCode().toUpperCase());
			String veriCode = stringRedisTemplate.opsForValue().get(VeriCodeUtil.getVeriCodeKey(request.getVeriKey(), request.getVeriCode()));
			if(request.getVeriCode().equals(veriCode)){
				result.setBizException(BizException.SUCCESS.newInstance("验证成功"));
			}
		}catch(Exception e){
			result.setBizException(e);
		}finally{
			//删除验证码
			if(StringUtils.isNotBlank(request.getVeriKey())&&StringUtils.isNotBlank(request.getVeriCode())){
				stringRedisTemplate.delete(VeriCodeUtil.getVeriCodeKey(request.getVeriKey(), request.getVeriCode()));
			}
			log.info("end 对比验证码是否合法,结果={}",result);
		}
		return result;
	}
}
